import React from "react";

const Index = () => {
    // 初始化路由跳转对象
    const navigate = React.$Router.useNavigate()

    const [searchParams, setSearchParams] = React.$Router.useSearchParams()

    const [action, setAction] = React.useState(searchParams.get('action'))

    //允许请求监听器
    const [listen, setListen] = React.useState(true)

    //搜索信息
    const [search,setSearch] = React.useState(React.$Cookies.load('Search')?React.$Cookies.load('Search'):'')

    let value = React.useRef(search)

    React.useEffect(()=>{
        value.current = search
    })

    // 返回商品数据
    const [list, setList] = React.useState([])

    let timer = null

    function setValue(value) {
        if(timer){
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            console.log(value);
            React.$Cookies.save('Search',value,'/')
            setList([])
            setSearch(value)
            page.current = 1
            setFinished(false)
        }, 1500)
        
    }

    // ref对象
    const listRef = React.useRef(null)

    let data = []

    const [finished, setFinished] = React.useState(false)

    // 用ref定义分页的值，可以每次拿到最新
    let page = React.useRef(1)

    // 获取商品数据
    const getProductData = async () => {
        let result = await React.$Api.ProductIndex({ page: page.current,search })

        if (result) {
            if (result.code === 1) {
                setList(list.concat(result.data))

                page.current = page.current + 1
                setListen(true)
            } else {
                React.$Vant.Toast.info(result.msg)
                setFinished(true)
                setListen(true)
                return false
            }
        }
    }

    // 选中商品的方法
    const Selected = (item) => {
        React.$Cookies.save('Product', item, { path: '/' })
        navigate(-1)
    }

    // 组件
    const Items = () => {
        if (action === 'add') {
            // 说明从租赁下单那边过来的
            return list.map((item, index) => {
                return (
                    <li key={index}>
                        <a onClick={(e) => Selected(item, e)}>
                            <img src={item.thumb_cdn} alt="" />
                            <p>{item.name}</p>
                            <span>{item.rent_price}</span>
                        </a>
                    </li>
                )
            })
        }

        if (action === 'home') {
            return list.map((item, index) => {
                return (
                    <li key={index}>
                        <React.$Router.NavLink to={'/product/product/info?id=' + item.id}>
                            <img src={item.thumb_cdn} alt="" />
                            <p>{item.name}</p>
                            <span>{item.rent_price}</span>
                        </React.$Router.NavLink>
                    </li>
                )
            })
        }
    }

    // 下拉刷新的方法
    const Refresh = () => {
        setList([])
        page.current = 1
        setFinished(false)

        return new Promise((resolve) => {
            setTimeout(() => {
                React.$Vant.Toast.info('刷新成功')
                resolve(true)
            }, 1000)
        })
    }

    // 上拉加载数据
    const load = () => {
        if (listen) {
            getProductData()
            setListen(false)
        }
    }

    const onBack = () => {
        React.$Cookies.remove('Search','','/')
        navigate(-1)
    }

    const Nav = () => {
        if (action === 'add') {
            return (
                <React.$Vant.Sticky>
                    <React.$Vant.NavBar
                        title='商品大全'
                        leftText='返回'
                        onClickLeft={onBack}
                    />
                </React.$Vant.Sticky>
            )
        }

        if (action === 'home') {
            return (
                <>
                    <React.$Vant.Sticky>
                        <React.$Vant.NavBar
                            title='商品大全'
                            leftText='返回'
                            onClickLeft={onBack}
                        />
                    </React.$Vant.Sticky>

                    <React.$Vant.Search value={value.current}  onChange={(e) => setValue(e)} placeholder="请输入搜索关键词" />
                </>
            )
        }
    }

    return (
        <>
            <Nav />

            {/* 列表 */}
            <React.$Vant.PullRefresh onRefresh={Refresh} onRefreshEnd={() => listRef.current?.check()}>
                <React.$Vant.List ref={listRef} onLoad={load} offset={5} finished={finished}>
                    <div className="left_kuangs">
                        <ul>
                            <Items />
                        </ul>
                    </div>
                </React.$Vant.List>
            </React.$Vant.PullRefresh>




            {/* 占位 */}
            <div style={{ height: ".75rem" }}></div>
        </>
    )
}

export default Index;